<?php

/**
 * @Author: king
 * @Date:   2019-05-30 15:44:18
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-03 22:53:18
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use DB;
use AstroTool\Cache\CacheManage;
use Cache;

class LanmeiCounselorLevel extends Model
{
    protected $table = 'counselor_level';

    /**
     * 在数据库中获取咨询师等级数据
     * @param $type
     * @return array
     * @throws ApiException
     */
    protected static function getCounselorLevelInData($type)
    {
        try
        {
            $data = self::where('status', 1)->where('type', $type)
                ->get(['type','level','integral','price','name')->keyBy('level')->toArray();

            // 对值进行json_decode处理
            $data = array_map(function ($v)
            {
                return json_encode($v, true);
            }, $data);
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $data;
    }

    /**
     * @param $type 类型 1占星 2占卜
     * @param string $level 指定等级 为空 获取全部
     * @return array|bool|mixed
     * @throws \Exception
     */
    public static function getCounselorLevel($type, $level = '')
    {
        $data = CacheManage::getInstance()->setCacheConfig('counselor_level_config', $type)
            ->getDataAndSet(function () use ($type)
            {
                return self::getCounselorLevelInData($type);
            }, $level, 'details');

        // 对值进行json_decode处理
        $data = array_map(function ($v)
        {
            return json_decode($v, true);
        }, $data);

        return $data;
    }
}
